<?php


namespace app\common\cachemodel\live;


use app\common\cachemodel\ZlUserVip;
use app\common\lib\SensorsData;
use app\common\model\BaseCache;
use think\Cache;
use think\Db;
use think\Log;
use XznsTools\cache\CacheManage;

class LiveAwardAcitveRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_award_acitve_record';

    protected $cacheModel = 'live.award_active';

    public $activeJoinType = [ // 参与类型 1=>发送任意弹幕 2=>发送指定弹幕 3=>点赞
        1 => '发送任意弹幕',
        2 => '发送指定弹幕',
        3 => '点赞',
    ];

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('a.id', $ids);
            } else
            {
                $this->where('a.live_id', $type[0])->order('id', $sortType);
            }

            $data = $this->alias('a')->join('wechat_backup_07_18_14_43_00.live_award la', 'la.id=a.award_id')
                ->join('wechatadmin.system_admin_user au', 'a.aid=au.id', 'LEFT')
                ->column('a.id active_id,la.name award_name,la.type award_type,la.cid award_cid,a.live_id,a.live_record_id,a.status,a.user_group_type,a.type,a.time,a.num,a.award_id,a.coupon_expire_time,a.message,a.create_time,au.username', 'a.id');

            return $data;
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    public function updateData(int $id, array $data, int $expire_time)
    {
        try
        {
            $this->whereIn('id', $id)->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCacheTime($expire_time)->setCache($data);
        }
        catch (\Exception $e)
        {
            Log::write("直播间抽奖活动更新失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }
    }

    /**
     * 获取抽奖记录
     * @param $liveId
     * @return array|mixed
     * @throws \Exception
     */
    public function getRecordLists($liveId)
    {
        $pageData = $this->getListPage($liveId);

        $resData = [];
        foreach ($pageData['data'] as $datum)
        {
            $resData[] = [
                'id' => $datum['id'],
                'title' => $datum['award_name'] . '抽奖',
                'time' => date('Y-m-d H:i:s', $datum['create_time']),
                'target' => '',
                'link' => '',
            ];
        }

        $pageData['data'] = $resData;

        return $pageData;
    }

    public function rmListCache($liveId)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveId)->rmListPageCache();
    }

    /**
     * 获取当前抽奖活动信息
     * @param int $liveId
     * @return array|bool
     * @throws \Exception
     */
    public function getNewAwardAcitveInfo(int $liveId)
    {
        // // 抽奖活动 缓存初始化 测试
        // CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveId)
        //     ->setCacheKeyDetail('now_active', $liveId)->setCacheType('string')->setCacheTime(3600)->setCache(1, 'now_active', false);
        $activeId = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveId)
            ->setCacheKeyDetail('now_active', $liveId)->setCacheType('string')->getCache([], 'now_active');

        if ($activeId)
        {
            return $this->getInfoById($activeId);
        } else
        {
            return null;
        }
    }

    /**
     * 获取直播间详情 抽奖活动信息
     * @param $liveId
     * @return array|null
     * @throws \Exception
     */
    public function getHomeNewAwardAcitveInfo($liveId): ?array
    {
        $activeInfo = $this->getNewAwardAcitveInfo($liveId);

        if (!$activeInfo)
        {
            return null;
        }

        if ($activeInfo['status'] == 1)
        { // 活动进行中
            $list = [
                [
                    'title' => '参与方式：',
                    'des_info' => [
                        'name' => $this->activeJoinType[$activeInfo['type']],
                        'target' => '',
                        'link' => '',
                        'is_show_left_time' => 0,
                    ]
                ],
                [
                    'title' => '',
                    'des_info' => [
                        'name' => '',
                        'target' => '',
                        'link' => '',
                        'is_show_left_time' => 0,
                    ]
                ],
                [
                    'title' => '时间',
                    'des_info' => [
                        'name' => $activeInfo['time'] . '分钟',
                        'target' => '',
                        'link' => '',
                        'is_show_left_time' => 1,
                    ]
                ],
                [
                    'title' => '奖品',
                    'des_info' => [
                        'name' => $activeInfo['award_name'],
                        'target' => 'local',
                        'link' => $activeInfo['award_type'] == 1 ? "live_gift_position?id={$activeInfo['award_cid']}&need_auth=0" : 'empty',
                        'is_show_left_time' => 0,
                    ]
                ],
                [
                    'title' => '数量',
                    'des_info' => [
                        'name' => $activeInfo['num'] . '人',
                        'target' => '',
                        'link' => '',
                        'is_show_left_time' => 0,
                    ]
                ],
            ];

            if ($activeInfo['type'] == 2)
            {// 指定弹幕
                $a = [
                    [
                        'title' => '指定弹幕：',
                        'des_info' => [
                            'name' => $activeInfo['message'],
                            'target' => 'local',
                            'link' => 'live_comment?text=' . urlencode($activeInfo['message']) . '&need_auth=2',
                            'is_show_left_time' => 0,
                        ]
                    ]
                ];
                array_splice($list, 1, 0, $a);
            }

            $awardActiveInfo = [
                'status' => 1,
                'award_info' => [
                    'id' => (int)$activeInfo['id'],
                    'title' => '主播抽奖',
                    'continue_second' => $activeInfo['create_time'] + ($activeInfo['time'] * 60) - time(),
                    'list' => $list
                ]
            ];
        } else
        {
            $continueSecond = $activeInfo['create_time'] + ($activeInfo['time'] * 60 + 30) - time(); // 持续显示时间
            if ($continueSecond < 0)
            {// 活动已结束 并且不显示
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveId)
                    ->setCacheKeyDetail('now_active', $liveId)->rmCache('now_active');

                return null;
            } else
            {// 活动已结束 继续显示
                $awardUsers = (new LiveAwardResultUser())->getAwardActiveResult((int)$activeInfo['id']);

                $resAwardUsers = [];
                foreach ($awardUsers as $uid => $awardUserItem)
                {
                    $resAwardUsers[] = [
                        'uen' => $awardUserItem['uen'],
                        'nickname' => $awardUserItem['nickname'],
                    ];
                }

                // 获取中奖用户信息
                $awardActiveInfo = [
                    'status' => 2,
                    'award_info' => [
                        'id' => (int)$activeInfo['id'],
                        'award_name' => $activeInfo['award_name'],
                        'continue_second' => $continueSecond, // 等待消失时间 秒
                        'award_users' => $resAwardUsers,
                        'target' => 'local',
                        'link' => $activeInfo['award_type'] == 1 ? "live_gift_position?id={$activeInfo['award_cid']}&need_auth=0" : 'discount_coupon_center?need_auth=2',
                    ]
                ];
            }
        }

        return $awardActiveInfo;
    }

    /**
     * 参与抽奖活动
     * @param $liveId int
     * @param int $liveRecordId
     * @param $uid  int
     * @param $type int 类型 1=>发消息 2=>点赞
     * @param $message string
     * @throws \Exception
     */
    public function awardActiveAdd(int $liveId, int $liveRecordId, int $uid, int $type, string $message = ''): void
    {
        $activeInfo = $this->getNewAwardAcitveInfo($liveId);

        if ($activeInfo && $activeInfo['live_record_id'] == $liveRecordId && $activeInfo['status'] == 1 &&
            (($type === 1 && in_array($activeInfo['type'], [1, 2], false)) || ($type === 2 && $activeInfo['type'] == 3))
        )   // 状态 进行中 且 参与方式 符合
        {
            if ($activeInfo['user_group_type'] == 2)
            {// 如果参与人群 是 VIP   判断用户是否是VIP
                $vipLevel = (new ZlUserVip())->getUserVipLevel($uid);
                if ($vipLevel < 1)
                {   // 不是VIP 则返回
                    return;
                }
            }

            if ($activeInfo['type'] == 2 && $message !== $activeInfo['message'])
            {// 如果参与方式是指定弹幕 且 弹幕不符合
                return;
            }

            // 判断用户是否参与了活动  已经参与了则返回
            if (Cache::get('live:award_active:is_in:' . $activeInfo['active_id'] . ':' . $uid, false))
            {
                return;
            }
            // 写入记录
            $tableName = 'live_award_active_user_' . $liveRecordId;// 直播间抽奖活动参与表
            if ($this->initTable($tableName))
            {
                try
                {
                    $d = [
                        'uid' => $uid,
                        'live_id' => $liveId,
                        'live_record_id' => $liveRecordId,
                        'award_acitve_id' => $activeInfo['active_id'],
                        'create_time' => time(),
                    ];

                    Db::table('`live_data`.' . $tableName)->insertGetId($d);
                    // 缓存记录用户已参与活动
                    Cache::set('live:award_active:is_in:' . $activeInfo['active_id']. ':' . $uid, true, 86400);   // 活动抽奖ID

                    $anchInfo = (new LiveAnchorInfo())->getInfoById($liveId);
                    $sensorsTrackData = [   // 神策打点数据
                        'hoster_name' => $anchInfo['name'] ?? '',
                        'live_id' => $liveId,
                        'live_record_id' => $liveRecordId,
                        'award_name' => $activeInfo['award_name'],  // 奖品名称
                        'award_conditions' => $this->activeJoinType[$activeInfo['type']],    // 点赞、任意弹幕、指定弹幕
                    ];
                    SensorsData::track($uid, true, 'LiveAwardParticipation', $sensorsTrackData);
                }
                catch (\Exception $e)
                {
                    Log::write("直播间抽奖活动参与用户写入失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                }
            }
        }
    }

    /**
     * 初始化活动参与用户表
     * @param string $tableName 表名
     * @return bool
     */
    public function initTable(string $tableName): bool
    {
        $cacheKey = 'table_exist:' . $tableName;
        $tableExist = Cache::get($cacheKey, 0);

        if ($tableExist)
        {
            return true;
        }

        $isTable = Db::query('select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`="live_data" and `TABLE_NAME`="' . $tableName . '"');
        if (!$isTable)
        { // 表不存在则创建
            try
            {
                $str = "CREATE TABLE `live_data`.`{$tableName}` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `uid` int(11) NOT NULL DEFAULT 0 COMMENT '参与用户ID',
                          `live_id` int(11) NOT NULL DEFAULT 0 COMMENT '直播间ID',
                          `live_record_id` int(11) NOT NULL DEFAULT 0 COMMENT '直播间ID',
                          `award_acitve_id` int(11) NOT NULL DEFAULT 0 COMMENT '抽奖活动ID',
                          `create_time` bigint(15) NOT NULL DEFAULT 0 COMMENT '参与时间',
                          PRIMARY KEY (`id`),
                          KEY `uid` (`uid`)
                        )  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='直播弹幕信息'";
                // 创建数据库
                Db::execute($str);
            }
            catch (\Exception $e)
            {
                if (!strstr($e->getMessage(), 'already exists'))
                {
                    Log::write("直播间抽奖活动参与用户表创建失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                    return false;
                }
            }
        }

        Cache::set($cacheKey, 1, 86400);
        return true;
    }

    /**
     * 获取抽奖记录详情信息
     * @param $live_id
     * @param $id
     * @return array|null
     * @throws \Exception
     */
    public function getAwardActiveRecordInfo($live_id, $id)
    {
        $info = $this->getInfoById($id);

        if (empty($info) || $info['live_id'] != $live_id)
        {
            return null;
        }

        $awardInfo = (new LiveAward())->getInfoById($info['award_id']);


        $resData = [
            'common_list' => [
                [
                    'type' => 1,
                    'title' => '抽奖详情',
                    'desc' => ''
                ],
                [
                    'type' => 2,
                    'title' => '类型：',
                    'desc' => $awardInfo['type'] == 1 ? '礼物' : '优惠券'
                ],
                [
                    'type' => 2,
                    'title' => '奖品：',
                    'desc' => $awardInfo['award_name']
                ],
                [
                    'type' => 2,
                    'title' => '开启时间：',
                    'desc' => date('Y-m-d H:i:s', $info['create_time'])
                ],
                [
                    'type' => 2,
                    'title' => '参与人群：',
                    'desc' => $info['user_group_type'] == 1 ? '所有用户' : 'VIP用户'
                ],
                [
                    'type' => 2,
                    'title' => '获奖人数：',
                    'desc' => $info['num']
                ], [
                    'type' => 2,
                    'title' => '参与方式：',
                    'desc' => $this->activeJoinType[$info['type']]
                ], [
                    'type' => 2,
                    'title' => '操作人：',
                    'desc' => $info['username'] ?? ''
                ]
            ],
            'common_table_list' => []
        ];

        $awardResultData = [
            [
                'type' => 1,
                'type_1_data' => '中奖名单'
            ],
            [
                'type' => 2,
                'type_2_data' => [
                    '用户昵称',
                    '奖品',
                    '准了号',
                ]
            ],
        ];
        $awardResultInfo = (new LiveAwardResultUser())->getAwardActiveResult($id);
        foreach ($awardResultInfo as $item)
        {
            $awardResultData[] = [
                'type' => 3,
                'type_3_data' => [
                    $item['nickname'],
                    $awardInfo['award_name'],
                    $item['uen'],
                ]
            ];
        }

        $resData['common_table_list'][] = $awardResultData;

        return $resData;
    }
}
